<script setup>
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import utils from "../utils/utils";
const formInline = reactive({
  id: "",
  userName: "",
  state: "",
});

//获取全对象 类似于 options api 里面的 this
const { proxy } = getCurrentInstance();
//表格头
const columns = reactive([
  {
    label: "用户ID",
    prop: "userId",
  },
  {
    label: "用户名",
    prop: "userName",
  },
  {
    label: "用户邮箱",
    prop: "userEmail",
  },
  {
    label: "用户角色",
    prop: "role",
    formatter: (row, column, cellValue) => {
      return cellValue === 0 ? "管理员" : "普通用户";
    },
  },
  {
    label: "用户状态",
    prop: "state",
  },
  {
    label: "注册时间",
    prop: "createTime",
  },
  {
    label: "最后登录时间",
    prop: "lastLoginTime",
  },
]);
//用户列表
const userList = ref([]);
//分页的配置
const pager = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 10,
});
//查询的数据
const user = reactive({
  state: 0,
});
//获取用户列表
const getUserList = async () => {
  let params = { ...user, ...pager };
  const { page, list } = await proxy.$api.userList(params);
  // console.log(list)
  pager.total = page.total;
  userList.value = list;
  // const {...state} =userList.value
  userList.value.forEach((user) => {
    if (user.state == 1) {
      user.state = "在职";
    } else if (user.state == 2) {
      user.state = "离职";
    } else if (user.state == 3) {
      user.state = "试用期";
    }
    if (user.createTime) user.createTime = utils.formatDate(user.createTime);
    if (user.lastLoginTime)
      user.lastLoginTime = utils.formatDate(user.lastLoginTime);
  });
};

//查找功能
const handleQuery = () => {
  getUserList();
};
//重置
const handleReset = () => {
  proxy.$refs.form.resetFields();
};
//分页点击
const handleCurrentChange = (current) => {
  pager.pageNum = current;
  getUserList();
};
//删除单个用户
const handleDelete = async (row) => {
  const res = await proxy.$api.userDelete({
    userIds: [row],
  });
  console.log(res.nModified);
  if (res.nModified > 0) {
    proxy.$message.success("删除成功");
    getUserList();
  } else {
    proxy.$message.error("删除失败");
  }
};
//批量删除
const checkUsersIds = ref([]);
const toggleSelection = async () => {
  if (checkUsersIds.value.length == 0) {
    proxy.$message.error("请选择要删除的项");
    return;
  } else {
    const res = await proxy.$api.userDelete({
      userIds: checkUsersIds.value,
    });
    if (res.nModified > 0) {
      proxy.$message.success("删除成功");
      getUserList();
    } else {
      proxy.$message.error("删除失败");
    }
  }
};
const handleSelectionChange = (list) => {
  // console.log(list)
  let arr = [];
  list.forEach((ele) => {
    arr.push(ele.userId);
  });
  checkUsersIds.value = arr;
};
//新增
const showModal = ref(false);
const userForm = ref({
  userName: "",
  userEmail: "",
  mobile: "",
  job: "",
  state: 1,
  roleList: "",
  deptId: [
    {
      label: "橘子皮",
      children: [
        {
          label: "研发部门",
          children: [
            {
              label: "JAVA小组-1",
            },
          ],
        },
        {
          label: "前端部门",
        },
        {
          label: "测试部门",
        },
        {
          label: "UED部门",
        },
        {
          label: "大数据部门",
        },
        {
          label: "市场部门",
        },
      ],
    },
  ],
});
//form规则
const rules = reactive({
  userName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  userEmail: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  mobile: [
    {
      // pattern: /1[3-9]\d{9}/
      required: true,
      message: "请输入手机号",
      trigger: "blur",
    },
  ],
  job: [{ required: true, message: "请输入岗位", trigger: "blur" }],
  state: [{ required: true, message: "请选择状态", trigger: "blur" }],
  roleList: [{ required: true, message: "请选择角色", trigger: "blur" }],
  deptId: [{ required: true, message: "请选择所属部门", trigger: "blur" }],
});
const action = ref("add");
const handleUserAdd = () => {
  action.value = "add";
  showModal.value = true;
};

const roleList = ref([]);
const getRoleList = async () => {
  const res = await proxy.$api.getRoleList();
  roleList.value = res;
};
const deptList = ref([]);
const getDeptList = async () => {
  const res = await proxy.$api.getDeptList();
  deptList.value = res;
};
const handleClose = () => {
  showModal.value = false;
  proxy.$refs.addUserForm.resetFields();
};

const handleSubmit = () => {
  proxy.$refs.addUserForm.validate(async (valid) => {
    if (valid) {
      let params = JSON.parse(JSON.stringify(userForm.value));
      params.userEmail += "@Jason.com";
      params.action = action.value;
      let res = await proxy.$api.userSubmit(userForm.value);
      if (res) {
        showModal.value = false;
        if (action.value === "add") {
          proxy.$message.success("新增用户成功");
        } else {
          proxy.$message.success("修改用户成功");
        }
        proxy.$refs.addUserForm.resetFields();
        getUserList();
      }
    }
  });
};
const handleEdit = (row) => {
  console.log(row);
  action.value = "edit";
  showModal.value = true;
  proxy.$nextTick(() => {
    Object.assign(userForm.value, row);
  });
};
const handleCloseDialog = () => {
  proxy.$refs.addUserForm.resetFields();
  showModal.value = false;
};
//生命周期函数
onMounted(() => {
  getUserList();
  getRoleList();
  getDeptList();
});
</script>

<template>
  <div class="UserManager">
    <div class="UserManager-top">
      <el-form
        :inline="true"
        :model="formInline"
        ref="form"
        class="UserManager-form"
      >
        <el-form-item label="用户ID" prop="id">
          <el-input
            v-model="formInline.id"
            placeholder="请输入用户ID"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="formInline.userName"
            placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户状态" prop="state">
          <el-select v-model="formInline.state" placeholder="在职">
            <el-option label="所有" value="0"></el-option>
            <el-option label="在职" value="1"></el-option>
            <el-option label="离职" value="2"></el-option>
            <el-option label="试用期" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleReset()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="UserManager-main">
      <div class="UserManager-main-buttom">
        <el-button @click="handleUserAdd()">新增</el-button>
        <el-button @click="toggleSelection()">批量删除</el-button>
      </div>
      <el-table
        ref="multipleTable"
        :data="userList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        >
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="pager.total"
        class="pagination"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="新增用户"
      v-model="showModal"
      :before-close="handleCloseDialog"
    >
      <el-form
        class="adduser-form"
        :rules="rules"
        ref="addUserForm"
        :model="userForm"
      >
        <el-form-item label=" 用户名" prop="userName">
          <el-input
            v-model="userForm.userName"
            placeholder="请输入用户名称"
            :disabled="action == 'edit'"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input
            v-model="userForm.userEmail"
            placeholder="请输入用户邮箱"
            :disabled="action == 'edit'"
          >
            <template #append>
              <el-button>@jason.com</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            v-model="userForm.mobile"
            placeholder="请输入用户手机号"
          ></el-input>
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input
            v-model="userForm.job"
            placeholder="请输入用户岗位"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="userForm.state" placeholder="在职">
            <el-option label="所有" value="0"></el-option>
            <el-option label="在职" value="1"></el-option>
            <el-option label="离职" value="2"></el-option>
            <el-option label="试用期" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList">
          <el-select
            v-model="userForm.roleList"
            placeholder="请选择对应角色"
            multiple
          >
            <el-option
              v-for="role in roleList"
              :key="role._id"
              :value="role._id"
              :label="role.roleName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-cascader
            v-model="userForm.deptId"
            :options="deptList"
            :props="{ checkStrictly: true, value: _id, label: 'deptName' }"
            clearable
            placeholder="请选择所属部门"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
* {
  //   padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.UserManager {
  width: 100%;
  height: 100%;
  background-color: #dfdfdf;

  .UserManager-top {
    width: 100%;
    height: 100px;
    background-color: #fff;
    margin-bottom: 20px;
    padding: 20px;
    border-radius: 5px;

    .UserManager-form {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;

      .el-form-item {
        display: flex;
        align-items: center;

        .el-input {
          width: 200px;
          height: 40px;
        }

        .el-select {
          width: 200px;
          height: 40px;

          :deep(.el-select__wrapper) {
            height: 40px;
          }

          :deep(.el-select__selected-item) {
            padding: 10px;
            font-size: 14px;
          }
        }

        .el-button {
          width: 70px;
          height: 40px;
        }
      }
    }
  }

  .UserManager-main {
    width: 100%;
    height: calc(100% - 100px);
    background-color: #fff;

    .UserManager-main-buttom {
      width: 100%;
      height: 80px;
      padding: 20px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ccc;

      .el-button {
        height: 40px;
        color: #fff;
      }

      .el-button:first-of-type {
        width: 70px;
        background-color: #409eff;
      }

      .el-button:last-of-type {
        width: 100px;
        background-color: #f56c6c;
      }
    }

    .pagination {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      padding: 20px;
    }
  }

  :deep(.el-dialog) {
    width: 500px;
    height: 500px;

    .adduser-form {
      // width: 200px;
      padding: 10px;
      height: 100%;
      display: flex;
      flex-direction: column;

      .el-form-item {
        width: 100%;
        height: 50px;
        display: flex;
        align-items: center;

        label {
          width: 80px;
        }
      }

      .el-form-item:nth-of-type(5) {
        width: 250px;
      }
    }
  }
}
</style>
